package com.rikylee.bootreverseproxy.filter;

import com.rikylee.bootreverseproxy.config.MyRoutes;
import com.rikylee.bootreverseproxy.entity.RouteInstance;
import com.rikylee.bootreverseproxy.service.RoutingDelegateService;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class ForwardRoutingFilter extends OncePerRequestFilter implements Ordered {
  
  @Resource
  private MyRoutes routes;
  
  @Resource
  private RoutingDelegateService routingDelegate;
  
  @Override
  public int getOrder() {
    return 0;
  }
  
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    
    log.info("ForwardRoutingFilter doFilterInternal,request uri: {}", request.getRequestURI());
    String currentURL = StringUtils.isEmpty(request.getContextPath()) ? request.getRequestURI() :
        StringUtils.substringAfter(request.getRequestURI(), request.getContextPath());
    AntPathMatcher matcher = new AntPathMatcher();
    RouteInstance instance = routes.getRoutes().stream().filter(i -> matcher.match(i.getPath(), currentURL)).findFirst().orElse(new RouteInstance());
    
    if (instance.getUri() == null) {
      //转发的uri为空，不进行代理转发，交由过滤器链后续过滤器处理
      filterChain.doFilter(request, response);
    } else {
      // 创建一个service 去处理代理转发逻辑
      routingDelegate.doForward(instance, request, response);
      return;
    }
  }
}
